package com.yangchoi.jetpackcompose.ui.main.viewmodel

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.yangchoi.lib_base.base.BaseViewModel
import com.yangchoi.lib_base.network.ApiService
import com.yangchoi.lib_base.network.entity.ClassicChildItemEntity
import com.yangchoi.lib_base.network.entity.ClassicItemEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class ClassicViewModel @Inject constructor(private val apiService: ApiService) : BaseViewModel() {

    var viewState by mutableStateOf(ClassicState())
        set

    fun dispatch(event: ClassicEvent,position:Int = 0){
        when(event){
            ClassicEvent.OnInitClassic -> {
                launchFlow(
                    requestBlock = { apiService.getClassicTree()},
                    response = {
                        it?.let {
                            viewState = viewState.copy(classicList = it as ArrayList<ClassicItemEntity>,
                                childList = it[0].children as ArrayList<ClassicChildItemEntity>)
                        }
                    }
                )
            }

            ClassicEvent.OnChangeChildData -> {
                viewState = viewState.copy(childList = viewState.classicList!![position].children as ArrayList<ClassicChildItemEntity>)
            }
        }
    }

}

data class ClassicState(
    var classicList: ArrayList<ClassicItemEntity>? = null,
    var childList: ArrayList<ClassicChildItemEntity>? = null
)

sealed class ClassicEvent{
    object OnInitClassic : ClassicEvent()
    object OnChangeChildData : ClassicEvent()
}